import React, { useEffect, useState } from 'react'
import { Alert, Button, Empty, Modal, Form, Input, message, Spin, notification } from 'antd'
import { useNavigate } from 'react-router-dom'
import { CheckCircleOutlined, LoadingOutlined, CheckCircleTwoTone, ExclamationCircleTwoTone } from '@ant-design/icons'
import './index.scss'
import { info, renew, getLog, getKey, UrlState, createUrl, updataState } from '../../api'
import moment from 'moment'
var timer: NodeJS.Timeout
export default function Accounts() {
  const navigate = useNavigate()
  //创建续费窗口实例
  const [form] = Form.useForm()
  //续费窗口的打开状态
  const [showRenewModal, setShowRenewModal] = useState(false)
  //续费账号名
  const [renewAccount, setRenewAccount] = useState('')
  //日志窗口打开状态
  const [showLog, setShowLog] = useState(false)
  //日志数据
  const [logData, setLogData] = useState<Array<{ msg: string }>>([])
  //提示
  const [notificationApi, contextHolders] = notification.useNotification()
  //更新状态按钮
  const [updata, setUpdata] = useState(false)
  //保存account值
  const [account, setAccount] = useState('')
  const [data, setData] = useState<Array<{ id: number, creator: string, account: string, password: string, vip: string, online: number | null }>>([])
  useEffect(() => {
    info().then(res => {
      setData(res.data.date)
    })
  }, [])
  useEffect(() => {
    notificationApi['info']({
      message: "提示",
      description: '点击状态按钮可以更新状态(在状态正常的情况下也可以更新哦)',
      duration: 10
    })
  }, [])
  function time(str: string): string {
    return moment(str).format('YYYY-MM-DD')
  }
  //获取日志
  async function Log(account: string) {
    const res = await getLog(account)
    console.log(res.data.data)
    setLogData(res.data.data)
  }
  //点击续费确认按钮的回调
  async function confirmRecharge() {
    form.validateFields().then(async values => {
      const result = await renew(values.key, renewAccount)
      if (!result.data.code) {
        message.error(result.data.msg)
      } else {
        message.success(result.data.msg)
        setShowRenewModal(false)
        form.resetFields()
      }
    })
  }
  const [modal, contextHolder] = Modal.useModal();
  const [key, setKey] = useState('')
  const [qrUrl, setQrurl] = useState('')
  const [qrState, setQrstate] = useState(0)
  const [cookie, setCookie] = useState('')
  const confirm = () => {
    modal.confirm({
      title: '更新成功',
      icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
      content: '账号Cookie已更新成功',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        navigate('/home/accounts')
        window.location.reload()
      }
    });
  };
  const enterLoading = (index: number) => {
    if (qrState !== 4) return message.warning('请使用网易云音乐App扫码登录')
    updataState(account, cookie).then(res => {
      if (res.data.code) {
        confirm()
      } else {
        message.error(res.data.msg, 3)
      }
    })

  };
  //生成key并创建二维码
  function createQrcode() {
    setQrstate(1)
    getKey().then(res => {
      if (res.data.msg.body.code === 200) {
        setKey(res.data.msg.body.data.unikey)
        qrCreate(res.data.msg.body.data.unikey)
        getUrlState(res.data.msg.body.data.unikey)
      } else {
        message.warning('二维码生成异常，请稍后重试')
      }
    })
  }
  //生成登录key
  useEffect(() => {
    if (updata) {
      createQrcode()
    } else {
      clearInterval(timer)
    }

    return clearInterval(timer)
  }, [updata])
  //轮询登录状态
  function getUrlState(key: string) {
    timer = setInterval(() => {
      UrlState(key).then(res => {
        const { code } = res.data.msg?.body || 3
        switch (code) {
          case 800:
            setQrstate(3)
            clearInterval(timer)
            break;
          case 802:
            setQrstate(2)
            break
          case 803:
            setQrstate(4)
            clearInterval(timer)
            setCookie(res.data.msg.body.cookie)
            break
          default:
            break;
        }
      })
    }, 1000)
  }
  //获取二维码地址
  async function qrCreate(keys = key) {
    const { data } = await createUrl(keys)
    if ((data.code) === 0) return message.warning('二维码生成异常，请稍后重试')
    setQrurl(data.msg.body.data.qrimg)
    setQrstate(0)
  }
  return (
    <div className='accounts'>
      <div className='accounts-top'>
        <div className='account'>
          账号
        </div>
        <div className='state'>状态</div>
        <div className='vip'>到期时间</div>
        <div className='operate'>操作</div>
      </div>
      <div className='accounts-list'>
        {contextHolders}
        {contextHolder}
        {
          !data[0] ? <Empty description='数据为空'></Empty> : data.map((item, index) => {
            return (
              <div className='list' key={item.id}>
                <Modal
                  open={showRenewModal}
                  title='续费'
                  okText='续费'
                  cancelText='取消'
                  width={'80%'}
                  onCancel={() => { setShowRenewModal(!showRenewModal) }}
                  onOk={confirmRecharge}
                >
                  <Form
                    name="wrap"
                    labelAlign="left"
                    wrapperCol={{ flex: 1 }}
                    colon={false}
                    form={form}
                  >
                    <Form.Item style={{ width: '100%' }} label="卡密" help='请输入卡密' name="key" rules={[{ required: true }]}>
                      <Input />
                    </Form.Item>
                  </Form>
                </Modal>
                <Modal
                  open={showLog}
                  title='日志'
                  okText='确定'
                  cancelText='取消'
                  width={'90%'}
                  onCancel={() => { setShowLog(!showLog) }}
                  onOk={() => { setShowLog(!showLog) }}
                  className='log'
                >
                  {
                    !logData[0] ? <Spin></Spin> : logData.map((item) => <div style={{ padding: '10px' }}>{item.msg}</div>)
                  }
                </Modal>
                <Modal
                  open={updata}
                  title='更新状态(请使用网易云音乐APP扫码)'
                  okText='确定'
                  cancelText='取消'
                  width={'70%'}
                  onCancel={() => { setUpdata(!updata) }}
                  onOk={() => { enterLoading(0) }}
                  className='stateUpdata'
                >
                  <div className='qrurl-box'>
                    <div className='remind' style={{ display: qrState !== 0 ? 'flex' : 'none' }}>
                      {/* 为1时为等待 */}
                      <LoadingOutlined style={{ display: qrState === 1 ? 'inline-block' : 'none' }}></LoadingOutlined>
                      {/* 为2时为已扫描 */}
                      <div className='scanned' style={{ display: qrState === 2 ? 'flex' : 'none' }}>
                        <CheckCircleTwoTone twoToneColor="#52c41a" style={{ fontSize: 20 }} />
                        <p>已扫描，待确认</p>
                      </div>
                      {/* 为3时为超时 */}
                      <div className='scanned' onClick={createQrcode} style={{ display: qrState === 3 ? 'flex' : 'none' }}>
                        <ExclamationCircleTwoTone twoToneColor="red" style={{ fontSize: 20 }} />
                        <p>超时，点击刷新</p>
                      </div>
                      {/* 为4时登录成功 */}
                      <div className='scanned' style={{ display: qrState === 4 ? 'flex' : 'none' }}>
                        <CheckCircleTwoTone twoToneColor="#52c41a" style={{ fontSize: 20 }} />
                        <p>登录成功</p>
                      </div>
                    </div>
                    <img src={qrUrl} alt="" />
                  </div>
                </Modal>
                <div className='account'>{item.account}</div>
                <div className='state'>{<Alert onClick={() => { setUpdata(!updata); setAccount(item.account) }} message={item.online ? '正常' : '掉线'} type={item.online ? "success" : 'error'} />}</div>
                <div className='vip'>{time(item.vip)}</div>
                <div className='operate'>
                  <Button type="primary" onClick={() => { navigate(`../control?account=${item.account}`) }}>管理</Button>
                  <Button type="primary" onClick={() => { setShowRenewModal(!showRenewModal); setRenewAccount(item.account) }}>续费</Button>
                  <Button type="primary" onClick={() => { setShowLog(!showLog); Log(item.account) }}>日志</Button>
                </div>
              </div>
            )
          })
        }
      </div>
    </div>
  )
}
